package groups;

import beans.SessionManagedBean;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.CustomScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import lecture.Lecture;
import user.User;
import user.UserAdminManagedBean;

/**
 *
 * @author Thorsten Ludwig
 */

@ManagedBean(name="viewExerciseGroupsBean")
@CustomScoped(value="#{window}")
public class ViewExerciseGroupsManagedBean {
    
    private ExerciseGroup ownGroup;
    
    public ViewExerciseGroupsManagedBean() {
        this.ownGroup = this.getOwnGroup();
    }
    
    
    public String group() {
        if (this.ownGroup == null) 
            return "Keine Übungsgruppe";
        return this.ownGroup.getName();
    }
    
    public boolean isInGroup(ExerciseGroup eg) {
        return (this.ownGroup == eg);
    }
    
    public List<String> getOwnStudents() {
        FacesContext c = FacesContext.getCurrentInstance();
        SessionManagedBean sb = c.getApplication().evaluateExpressionGet(c, "#{sessionBean}", SessionManagedBean.class);
        User user = sb.getUser();
        UserAdminManagedBean ua = c.getApplication().evaluateExpressionGet(c, "#{userAdminBean}", UserAdminManagedBean.class);
        Lecture lecture = sb.getLectureBean().getLecture();
        List<String> list = new ArrayList<String>();
        for (ExerciseGroup eg: lecture.getInfo().getExerciseGroups()) {
            if (eg.getLeaders().contains(user.getUsername())) {
                list.add("Übungsgruppe " + eg.getName());
                for (String student: eg.getStudents()) {
                    User u = ua.getUser(student);
                    String line = u.getFirstName() + " " + u.getLastName() + " " + u.getEmail();
                    list.add(line);
                    System.out.println(line);
                }
                list.add("");
            }
        }
        return list;
    }
    
    private ExerciseGroup getOwnGroup() {
        FacesContext c = FacesContext.getCurrentInstance();
        SessionManagedBean sb = c.getApplication().evaluateExpressionGet(c, "#{sessionBean}", SessionManagedBean.class);
        User user = sb.getUser();
        Lecture lecture = sb.getLectureBean().getLecture();
        
        for (ExerciseGroup eg: lecture.getInfo().getExerciseGroups()) {
            if (eg.getStudents().contains(user.getUsername()))
                return eg;
            else if (eg.getLeaders().contains(user.getUsername()))
                return eg;
        }    
        return null;
    }
    
}
